<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Blog_model extends CI_Model
{
	// Get the amount of rows of blogposts
	public function get_all_blogposts_rows()
	{
		$query = $this->db->get("blog");
		
		if($query->num_rows() > 0)
		{
			return $query->num_rows();
		}
		return false;
	}
	
	// Inserts a new blogpost
	public function post_new_blogpost($userId, $headline, $message)
	{
		$data = array(
		   'userId'		=> $userId ,
		   'headline'	=> $headline ,
		   'message'	=> $message);

		$this->db->insert('blog', $data); 
	}
	
	// Retrives limited blogresults
	public function get_blog_limited($startRow, $perPage)
	{	
		$this->db->select('blog.*, COUNT(blog_comments.commentId) as comments', FALSE)
			->join('blog_comments', 'blog_comments.blogId=blog.id', 'left')
			->group_by('blog.id')
			->order_by('blog.posted desc');
			
		$query = $this->db->get('blog',$perPage,$startRow);
		
		if($query->num_rows() > 0)
		{
			$blogArray = array();
			foreach($query->result_array() as $row)
			{
				$object = new BlogPost($row['id'], $row['userId'], $row['posted'], $row['headline'], $row['message'], $row['comments']);
				$blogArray[] = $object;
			}
			return $blogArray;
		}
		return false;
	}
	
	// Single blogpost
	public function get_single_blogpost($blogId)
	{
		$query = $this->db->get_where("blog", array("id" => $blogId));
		if($query->num_rows() == 1)
		{
			$row = $query->row();
			$object = new BlogPost($row->id, $row->userId, $row->posted, $row->headline, $row->message, null);
		 	return $object;
		}
		return false;
	}
	
	// Comments for blogpost
	public function get_blogpost_comments($blogId)
	{
		$this->db->order_by("blog_comments.posted", "asc");
		$this->db->join('users', 'users.id=blog_comments.userId', 'inner');
		
		$query = $this->db->get_where("blog_comments", array('blogId' => $blogId));
		
		if($query->num_rows() > 0)
		{
			$commentsArray = array();
			foreach($query->result_array() as $row)
			{
				$object = new BlogComment($row['commentId'], $row['blogId'], $row['username'], $row['posted'], $row['comment']);
				$commentsArray[] = $object;
			}
			return $commentsArray;
		}
		return false;
	}
	
	// Insert blog comment
	public function post_new_blog_comment($blogId, $userId, $comment)
	{
		$data = array(
		   'blogId'		=> $blogId ,
		   'userId'		=> $userId ,
		   'comment'	=> $comment);

		$this->db->insert('blog_comments', $data); 
	}
}